import Taro, {Component} from '@tarojs/taro'
import {View, Text ,Image , Button , Picker} from '@tarojs/components'

import {
  AtInput,
  AtForm,
  AtTextarea,
  AtRadio
} from 'taro-ui'

import './jobPost.scss'

import DataManager from '../../utils/DataManager.js'

import warnIcon from '../../image/ic_warn.png'
import locationIcon from '../../image/ic_location.png'

import {base_url} from "../../network/config";

import CustomRadio from '../../component/CustomRadio/customRadio'
import arrowImage from '../../image/ic_arrow_right.png'

let isCommitEnable = true;
export default class jobPost extends Component{

  config = {
    navigationBarTitleText: '发布招聘'
  }

  constructor(props) {
    super(props)
    this.state = {
      inputJobName: '',
      inputJobDesc:'',
      inputJobSalary:'',
      inputJobCount:'',
      inputJobCondition:'',
      inputJobDuty:'',
      inputJobLongitude:'',
      inputJobLatitude:'',
      inputJobAddress:'',
      inputJobMobile:'',
      isBusiness:'',
      agree:true,
      protocolShow :false,
      topPriceList:[],
      chosenTop:'暂未置顶',
      chosenTopValue:'',
      chosenTopCode:'',
      payWay:0, //   0微信支付  1积分支付
      integral:''
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentDidShow(){
    console.log('-------componentDidShow-------------')
    this.setState({
      isBusiness:DataManager.getIsBusiness(),
      inputJobMobile: DataManager.getBusinessMobile(),
    })
    this.loadTopList()
    this.loadUserDetail();
  }

  loadUserDetail(){
    let _this = this;

    let url = base_url + 'rest/user/userDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
      },
      method: 'GET',
      success(res) {
        console.log('userDetail=========' + JSON.stringify(res))
        if (res.data && res.data.data){
          _this.setState({
            integral : res.data.data.integral
          })
        }
      }
    })
  }

  loadTopList(){
    let _this = this;
    let url = base_url + 'stateless/dict/dictList'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        type:'top'
      },
      method: 'GET',
      success(res) {
        console.log('top------------' + JSON.stringify(res))
        let topList = [];
        if (res.data.data){
          topList = topList.concat(res.data.data);
        }
        _this.setState({
          topPriceList:topList,
        })
      }
    })
  }

  onChooseLocation = () =>{
    Taro.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']) {
          Taro.authorize({
            scope: 'scope.userLocation',
            success() {

            },
          })
        }
      }
    })
    let _this = this;
    Taro.chooseLocation({
      success (res) {
        _this.setState({
          inputJobAddress : res.address,
          inputJobLongitude : res.longitude,
          inputJobLatitude : res.latitude
        })
      }
    })
  }

  onNameChange = (name) =>{
    this.setState({
      inputJobName: name
    })
  }

  onDescChange = (desc) =>{
    this.setState({
      inputJobDesc: desc
    })
  }

  onCountChange = (count) =>{
    this.setState({
      inputJobCount: count
    })
  }

  onSalaryChange = (salary) =>{
    this.setState({
      inputJobSalary: salary
    })
  }

  onMobileChange = (mobile) =>{
    this.setState({
      inputJobMobile: mobile
    })
  }

  onConditionChange = (e) =>{
    this.setState({
      inputJobCondition: e.target.value
    })
  }

  onDutyChange = (e) =>{
    this.setState({
      inputJobDuty: e.target.value
    })
  }

  onJobAddressChange = (address) =>{
    this.setState({
      inputJobAddress: address
    })
  }

  goToShopRegister = () => {
    Taro.navigateTo({
      url : '/pages/me/shopRegister'
    })
  }

  onHandleAgree = () =>{
    const agree = this.state.agree
    this.setState({agree:!agree})
  }

  commitParamsCheck(){
    let checked = false;
    let hint = '';
    if (!this.state.inputJobName){
      hint = '请填写职位名称'
    } else if (!this.state.inputJobDesc){
      hint = '请填写职位介绍'
    } else if (!this.state.inputJobCount){
      hint = '请填写招聘人数'
    } else if (!this.state.inputJobSalary){
      hint = '请填写职位薪资'
    } else if (!this.state.inputJobMobile){
      hint = '请填写联系方式'
    } else if (!this.state.inputJobAddress){
      hint = '请选择工作地址'
    } else if (!this.state.inputJobCondition){
      hint = '请填写岗位要求'
    } else if (!this.state.inputJobDuty){
      hint = '请填写岗位职责'
    } else {
      checked = true;
    }
    if (!checked){
      Taro.showToast({
        title:hint,
        icon:'none'
      })
    }

    return checked;
  }


  handleCommit = () => {
    if (!isCommitEnable){
      return;
    }
    if (!this.state.isBusiness){

      return;
    }
    if (!this.commitParamsCheck()){
      return;
    }
    isCommitEnable = false;

    if (this.state.chosenTopValue && this.state.payWay == 0){ // 先支付
      this.onPayForPost();
    } else {
      this.onJobPost();
    }
  }

  onPayForPost(){
    let _this = this;
    Taro.request({
      url:base_url + 'rest/order/createOrder',
      data:{
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'wechat',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        openId:DataManager.getOpenId(),
        amount:this.state.chosenTopValue,
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success(obj){
        if (obj.data.status == 'success') {
          if (obj.data.data){
            let timeStamp = obj.data.data.timeStamp;
            let nonceStr = obj.data.data.nonceStr;
            let payPackage = obj.data.data.package;
            let signType = obj.data.data.signType;
            let paySign = obj.data.data.paySign;

            Taro.requestPayment({
              'timeStamp': timeStamp,
              'nonceStr': nonceStr,
              'package': payPackage,
              'signType': signType,
              'paySign': paySign,
              success(res){
                _this.onJobPost();
              },
              fail(res){
                Taro.showToast({
                  title:'支付失败',
                  icon:'none'
                })
                console.log('pay--failed----' + JSON.stringify(res))
                isCommitEnable = true;
              }
            })
          }
        } else {
          Taro.showToast({
            title: obj.data.message,
            icon: 'none',
            duration: 1000
          })
          isCommitEnable = true;
        }
      },
      fail(obj){
        Taro.showToast({
          title: '支付失败',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  onJobPost(){
    let params = {};
    params.peopleCount = this.state.inputJobCount;
    params.weixinId = DataManager.getWeiXinId();
    params.position = this.state.inputJobName;
    params.intro = this.state.inputJobDesc;
    params.condition = this.state.inputJobCondition;
    params.payScope = this.state.inputJobSalary;
    params.postDuties = this.state.inputJobDuty;
    params.address = this.state.inputJobAddress;
    params.mobile = this.state.inputJobMobile;
    if (this.state.inputJobLongitude) {
      params.longitude = this.state.inputJobLongitude;
    }
    if (this.state.inputJobLatitude){
      params.latitude = this.state.inputJobLatitude;
    }
    params.appId = 'KC876D98B30UA40CJSNHI689FB33SDW';
    params.digest = 'dda484557c12febe48139d8f44051c13';
    params.platform = 'android_c';
    params.token = DataManager.getToken();
    params.loginChannel = 'c';
    params.code = this.state.chosenTopCode;
    params.payType = this.state.payWay;

    console.log('post---params-----------' + JSON.stringify(params))

    let url = base_url + 'rest/pin/savePin'
    Taro.request({
      url:url,
      data: params,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success(res) {
        if (res.data && res.data.status == 'success'){
          Taro.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 1000
          });

          Taro.eventCenter.trigger('jobPost' ,[]);
          Taro.navigateBack({delta: 1});
        } else {
          Taro.showToast({
            title: '发布失败' + JSON.stringify(res),
            icon: 'none',
            duration: 1000
          })
        }
        isCommitEnable = true;
      },
      fail(obj){
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
        isCommitEnable = true;
      }
    })
  }

  handleShowProtocol = () =>{
    Taro.navigateTo({
      url:'/pages/protocol/jobProtocol'
    });
  }

  onTopSelect = (e) => {
    if (this.state.integral < this.state.topPriceList[e.detail.value].value) {
      this.setState({
        chosenTop: this.state.topPriceList[e.detail.value].name,
        chosenTopValue:this.state.topPriceList[e.detail.value].value,
        chosenTopCode:this.state.topPriceList[e.detail.value].code,
        payWay:0
      })
    } else {
      this.setState({
        chosenTop: this.state.topPriceList[e.detail.value].name,
        chosenTopValue:this.state.topPriceList[e.detail.value].value,
        chosenTopCode:this.state.topPriceList[e.detail.value].code
      })
    }
  }

  onTopCancel = () =>{
    this.setState({
      chosenTop: '暂未置顶',
      chosenTopValue:'',
      chosenTopCode:'',
    })
  }

  handlePayWayChange = (value) =>{
    this.setState({
      payWay:value,
    })
  }

  render(){
    let topStyle = this.state.isBusiness ? 'job-post-container-sub' : 'job-post-container-sub-top'

    let commitValue = '提交'
    if (this.state.chosenTopValue){
      if (this.state.payWay == 0) {
        commitValue= '需支付 ¥ ' + this.state.chosenTopValue + '元';
      } else if (this.state.payWay == 1){
        commitValue= '需支付 ' + this.state.chosenTopValue * 10 + '积分';
      }
    }

    let weiPay = {label: '微信支付', value: 0};
    let scoreLabel = '积分支付' + ' （剩余积分：' + this.state.integral + '）'
    let scoreDisable = this.state.integral < this.state.chosenTopValue * 10;
    let scorePay = {label:scoreLabel , value: 1 , disabled : scoreDisable};
    let payWayList = [weiPay , scorePay];

    return(
      <View className='job-post-container'>
        {!this.state.isBusiness ?
          <View className='job-post-not-business-container' onClick={this.goToShopRegister.bind(this)}>
            <Image className='job-post-warn-icon' src={warnIcon}></Image>
            <Text className='job-post-warn-hint'>成为商家后才可发布招聘信息，去成为商家 >></Text>
          </View> : null
        }
        <View className={topStyle}>
          <AtForm>
            <AtInput
              className='common-input'
              name='jobName'
              value={this.state.inputJobName}
              clear
              title='职位名称'
              type='text'
              placeholder='请填写职位名称'
              border
              maxlength={50}
              onChange={this.onNameChange.bind(this)}
            />
            <AtInput
              className='common-input'
              name='jobDesc'
              value={this.state.inputJobDesc}
              clear
              title='职位介绍'
              type='text'
              placeholder='请填写职位介绍'
              border
              maxlength={50}
              onChange={this.onDescChange.bind(this)}
            />
            <AtInput
              className='common-input'
              name='jobCount'
              value={this.state.inputJobCount}
              clear
              title='招聘人数'
              type='number'
              placeholder='请填写招聘人数'
              border
              maxlength={10}
              onChange={this.onCountChange.bind(this)}
            />
            <AtInput
              className='common-input'
              name='jobSalary'
              value={this.state.inputJobSalary}
              clear
              title='职位薪资'
              type='text'
              placeholder='请填写职位薪资'
              border
              maxlength={50}
              onChange={this.onSalaryChange.bind(this)}
            />
            <AtInput
              className='common-input'
              name='jobMobile'
              value={this.state.inputJobMobile}
              clear
              title='联系方式'
              type='number'
              placeholder='请填写联系方式'
              border
              maxlength={50}
              onChange={this.onMobileChange.bind(this)}
            />
            <AtInput
              className='common-input'
              name='jobAddress'
              value={this.state.inputJobAddress}
              title='工作地址'
              type='text'
              placeholder='请填写工作地址'
              border
              maxlength={50}
              onChange={this.onJobAddressChange.bind(this)}
            >
              <Image style='width: 20px;height: 20px;' src={locationIcon}  onClick={this.onChooseLocation.bind(this)}></Image>
            </AtInput>
          </AtForm>
          <View className='job-post-divider' style='margin-top:20px;'></View>
          <Text className='job-post-sub-title'>岗位要求</Text>
          <AtTextarea
            className='common-input-area'
            value={this.state.inputJobCondition}
            maxlength='300'
            placeholder='请填写岗位要求'
            onChange={this.onConditionChange.bind(this)}
          />
          <Text className='job-post-sub-title'>岗位职责</Text>
          <AtTextarea
            className='common-input-area'
            value={this.state.inputJobDuty}
            maxlength='300'
            placeholder='请填写岗位职责'
            onChange={this.onDutyChange.bind(this)}
          />
          <View className='job-post-divider'></View>
          <Picker
            mode='selector'
            range={this.state.topPriceList}
            rangeKey='name'
            value='0'
            onChange={this.onTopSelect.bind(this)}
            onCancel={this.onTopCancel.bind(this)}
          >
            <View className='job-post-top-container'>
              <Text className='job-post-top-text'>是否置顶</Text>
              <View className='job-post-top-right'>
                <Text className='job-post-top-text'>{this.state.chosenTop}</Text>
                <Image className='job-post-top-arrow' src={arrowImage}/>
              </View>
            </View>
          </Picker>
          <View className='job-post-divider'></View>

          {this.state.chosenTopValue && <AtRadio
            options={payWayList}
            value={this.state.payWay}
            onClick={this.handlePayWayChange.bind(this)}
          />}

          <View className='disclaimer'>
            <CustomRadio checked={this.state.agree} onClick={this.onHandleAgree.bind(this)}/>
            <View className='protocol-ele' onClick={this.handleShowProtocol.bind(this)}>我已阅读并同意《招聘发布协议》</View>
          </View>
        </View>
        <View className='job-post-commit-container' onClick={this.handleCommit.bind(this)}>
          <Button className='job-post-commit' disabled={!this.state.isBusiness || !this.state.agree}>{commitValue}</Button>
        </View>
      </View>
    )
  }

}


